package cn.yangliu.aspect;

import cn.yangliu.comm.BaseComponent;
import cn.yangliu.comm.tools.SpringUtil;
import cn.yangliu.service.LogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.Method;

/**
 * 作者 杨柳
 * 创建时间 2017-08-29 10:21
 */
public abstract class AbstractAspect extends BaseComponent {

    protected void doRecord(Throwable e, ProceedingJoinPoint joinPoint) throws Throwable {
        //根据当前运行时类获取Logger实例
        Logger logger = LoggerFactory.getLogger(joinPoint.getTarget().getClass());
        //打印异常信息
        logger.error(e.getMessage(), e);
        try {
            LogService logService = SpringUtil.getBean(LogService.class);
            logService.todo(e);
        } catch (Exception ex) {

        }
    }

    public boolean checkReturnJson(ProceedingJoinPoint joinPoint) {
        // 获取当前调用的方法
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        //判断是不是返回json的方法
        boolean isjson = false;
        ResponseBody responseBody = method.getDeclaredAnnotation(ResponseBody.class);
        if (responseBody != null) {
            isjson = true;
        } else {
            Class<?> clazz = joinPoint.getTarget().getClass();

            RestController restController = clazz.getAnnotation(RestController.class);

            if (restController != null) {
                isjson = true;
            }
        }
        return isjson;
    }
}
